package front

import (
	"encoding/json"
	red "github.com/gomodule/redigo/redis"
	"github.com/juju/errors"
	"qihuang/config"
	"qihuang/db/mysql"
	"qihuang/db/redis"
	"qihuang/loger"
	"qihuang/model"
	"qihuang/protocol"
	"strconv"
	"time"
	//"reflect"
)

type StandardParams struct {
	CreateTime string `json:"create_time"`
	ModifyTime string `json:"modify_time"`
	Status     int    `json:"status"`
	Age        string `json:"age"`
	KeyName    int    `json:"key_name"`
	KeyVal     string `json:"key_val"`
}

//文章详情
type StandardDetails struct {
	model.Standard
}

type Standards struct {
}

//添加文章
func (c *Standards) Add(params *StandardParams) (resp *protocol.Resp) {
	resp = &protocol.Resp{Status: 1, Msg: "", Data: ""}
	articles := model.Standard{
		CreateTime: time.Now().Format("2006-01-02 15:04:05"),
		ModifyTime: time.Now().Format("2006-01-02 15:04:05"),
		Status:     params.Status,
		Age:        params.Age,
		KeyName:    params.KeyName,
		KeyVal:     params.KeyVal,
	}

	//articles_contents := model.ArticlesContents{
	//	ShowType: params.ShowType,
	//	Contents: params.Contents,
	//}
	//if articles_contents.GetShowTypeName() == "" {
	//	resp.Msg = "文章内容显示类型错误"
	//	return resp
	//}
	//添加articles_contents
	db := mysql.Default().GetConn()
	defer db.Close()
	// 开始事务
	tx := db.Begin()
	//添加articles
	err := db.Model(model.Standard{}).Create(&articles).Error
	if err != nil {
		loger.Loger.Error(errors.ErrorStack(errors.Trace(err)))
		resp.Msg = "系统错误"
		tx.Rollback()
		return resp
	}
	////获取插入记录的Id
	//var article_id []int
	//db.Raw("select LAST_INSERT_ID() as id").Pluck("article_id", &article_id)
	//articles_contents.ArticleId = article_id[0]
	//err = db.Create(&articles_contents).Error
	//if err != nil {
	//	loger.Loger.Error(errors.ErrorStack(errors.Trace(err)))
	//	resp.Msg = "系统错误"
	//	tx.Rollback()
	//	return resp
	//}
	//提交事务
	tx.Commit()
	resp.Status = 0
	return resp
}

//分页获取文章列表mysql
func (c *Standards) GetListForMysql(page int, pageSize int, fields []string) (resp *protocol.Resp) {
	resp = &protocol.Resp{Status: 1, Msg: "", Data: ""}
	db := mysql.Default().GetConn()
	defer db.Close()
	offset := (page - 1) * pageSize
	topics := make([]model.Standard, 0)
	db = db.Where("status = ?", 0)

	if err := db.Select(fields).Offset(offset).Limit(pageSize).Order("id desc").Find(&topics).Error; err != nil {
		loger.Loger.Error(errors.ErrorStack(errors.Trace(err)))
		resp.Msg = "系统错误"
		return resp
	}
	resp.Status = 0
	resp.Data = topics
	return resp
}

//分页获取文章列表es
func (c *Standards) GetListForEs(page int, pageSize int, fields []string) (resp *protocol.Resp) {
	resp = &protocol.Resp{Status: 1, Msg: "", Data: ""}
	//esclient, err := es.Default()
	//if err != nil {
	//	loger.Loger.Error(errors.ErrorStack(errors.Trace(err)))
	//	resp.Status = -999
	//	resp.Msg = "系统错误"
	//	return resp
	//}
	//esconn := esclient.GetConn()
	//ctx := context.Background()
	topics := make([]model.Standard, 0)

	db := mysql.Default().GetConn()
	defer db.Close()
	offSet := pageSize * (page - 1)
	if err := db.Limit(pageSize).Offset(offSet).Where("status = 0").Find(&topics).Error; err != nil {
		loger.Loger.Error(errors.ErrorStack(errors.Trace(err)))
		loger.Loger.Error(errors.ErrorStack(errors.Trace(err)))
		resp.Status = 1
		resp.Msg = "系统错误"
		return resp
	}
	//
	//query := esconn.Search().
	//	Index("myblog").
	//	Type("mb_articles").
	//	Size(page_size).
	//	From((page-1)*page_size).
	//	Sort("modify_time", false).
	//	Pretty(true)
	//boolQuery := elastic.NewBoolQuery()
	//searchQuery := boolQuery.Must(elastic.NewTermQuery("status", 1))
	//if cate_id > 0 {
	//	searchQuery = searchQuery.Filter(elastic.NewTermQuery("cate_id", cate_id))
	//}
	//query = query.Query(searchQuery)
	//result, err := query.Do(ctx)
	//if err != nil {
	//	loger.Loger.Error(errors.ErrorStack(errors.Trace(err)))
	//	resp.Status = -999
	//	resp.Msg = "系统错误"
	//	return resp
	//}
	//var typ model.Articles
	////for _, item := range result.Each(reflect.TypeOf(typ)) { //从搜索结果中取数据的方法
	//for _, item := range result.Each(reflect.TypeOf(typ)) { //从搜索结果中取数据的方法
	//	t := item.(model.Articles)
	//	t.ModifyTime = helper.DateToDateTime(t.ModifyTime)
	//	t.CreateTime = helper.DateToDateTime(t.CreateTime)
	//	articles = append(articles, t)
	//
	//}
	resp.Status = 0
	resp.Data = topics
	return resp
}

//获取文章详情
func (c *Standards) GetStandardDetail(articleId int) (resp *protocol.Resp) {
	resp = &protocol.Resp{Status: 1, Msg: "", Data: ""}
	//articleContent := model.ArticlesContents{}
	topicDetails := StandardDetails{}
	redisConn := redis.RedisClient.Pool.Get()
	cacheKey := "talk_" + config.Configs.RedisCacheVersion + ":" + strconv.Itoa(articleId)
	if err := redisConn.Err(); err != nil {
		loger.Loger.Error(errors.ErrorStack(errors.Trace(err)))
	} else {
		cateCache, err := red.String(redisConn.Do("GET", cacheKey))
		if err != nil {
			loger.Loger.Error(errors.ErrorStack(errors.Trace(err)))
		} else {
			if cateCache != "" {
				err := json.Unmarshal([]byte(cateCache), &topicDetails)
				if err != nil {
					loger.Loger.Error(errors.ErrorStack(errors.Trace(err)))
				}
				resp.Status = 0
				resp.Data = topicDetails
				return resp
			}
		}
	}

	db := mysql.Default().GetConn()
	defer db.Close()
	if err := db.Where("id = ?", articleId).Where("status = ?", 0).First(&topicDetails).Error; err != nil {
		loger.Loger.Error(errors.ErrorStack(errors.Trace(err)))
		resp.Msg = "内容不存在"
		return resp
	}
	if topicDetails.Id <= 0 {
		resp.Msg = "内容不存在"
		return resp
	}
	//if err := db.Where("article_id = ?", articleId).First(&articleContent).Error; err != nil {
	//	loger.Loger.Error(errors.ErrorStack(errors.Trace(err)))
	//	resp.Msg = "系统错误"
	//	return resp
	//}
	resp.Status = 0
	//articleDetails.Contents = articleContent.Contents
	//articleDetails.ShowType = articleContent.ShowType
	cacheData, err := json.Marshal(topicDetails)
	if err == nil {
		redisConn.Do("set", cacheKey, string(cacheData))
		redisConn.Do("expire", cacheKey, 86400*3)
	}
	resp.Data = topicDetails
	return resp
}
